<template>
  <div class="page-content">
    <el-card shadow="never">
      <el-form ref="form" :model="formData" :rules="rules" label-width="150px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model.trim="formData.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item
            label="公司地址"
            prop="companyDetailAddress"
          >
            <el-cascader
              v-model="city"
              style="width: 100%"
              :props="regionProps"
              @change="onChangeRegion">
            </el-cascader>

            <el-input
              type="textarea"
              style="margin-top: 10px"
              placeholder="详细地址，街道，门牌等"
              v-model.trim="formData.companyDetailAddress"
              :rows="3"
            >
            </el-input>

          </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model.trim="formData.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model.trim="formData.contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="可供类目" prop="categoryName">
          <el-checkbox-group v-model="categoryChecked.list">
            <el-checkbox v-for="label in categoryList" :key="label" :label="label"></el-checkbox>
            <el-input v-model.trim="categoryChecked.other" placeholder="请输入其他可供类目"></el-input>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="推荐人">
          <el-input v-model.trim="formData.recommendUserName" placeholder="请输入推荐人" />
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { region } from '@/api/common';
import { create } from '@/api/purchase/supplier';

export default {
  name: 'supplierForm',

  data () {
    const checkAddress = (rule, value, callback) => {
      if (this.city.length !== 3) {
        callback(new Error('请选择城市'));
      } else {
        callback();
      }
    };
    const checkMobile = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'));
      } else if (!/^[0-9-]+$/.test(value)) {
        callback(new Error('请输入正确的电话号码'));
      } else {
        callback();
      }
    };
    const checkCategory = (rule, value, callback) => {
      const categoryChecked = this.categoryChecked;

      if (!categoryChecked.other && !categoryChecked.list.length) {
        callback(new Error('请选择可供类目或者填写其他类目'));
      } else {
        callback();
      }
    };

    return {
      formData: {
        companyName: '',
        companyProvinceCode: '',
        companyProvinceName: '',
        companyCityCode: '',
        companyCityName: '',
        companyCountyCode: '',
        companyCountyName: '',
        companyDetailAddress: '',
        contactName: '',
        contactPhone: '',
        categoryName: '',
        recommendUserName: '',
      },
      city: [],
      categoryChecked: {
        list: [],
        other: '',
      },
      categoryList: [
        '办公用纸',
        '办公设备',
        '办公耗材',
        '电脑及配件',
        '办公文具',
        '数码设备',
        '办公家电',
        '通讯设备',
        '办公家具',
        '生活日用',
        '食品饮料',
        '运动户外',
        '劳保劳防',
        '工程/服务',
      ],
      rules: {
        companyName: [{ required: true, message: '请输入公司名称' }],
        companyDetailAddress: [
          { required: true, message: '请选择并输入详细地址' },
          { validator: checkAddress },
        ],
        contactName: [{ required: true, message: '请输入联系人' }],
        categoryName: [{ required: true, validator: checkCategory }],
        contactPhone: [
          { required: true, message: '请输入收货电话' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      regionProps: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          this.getRegion(node.value ? node.value.code : 0, node.level === 2).then(resolve);
        },
      },
    };
  },

  methods: {
    async getRegion (parent = 0, leaf = false) {
      const list = await region(parent);
      return list.map(item => ({
        value: item,
        label: item.name,
        leaf: leaf,
      }));
    },

    onChangeRegion ($event) {
      this.formData.companyProvinceCode = $event[0].code;
      this.formData.companyCityCode = $event[1].code;
      this.formData.companyCountyCode = $event[2].code;

      this.formData.companyProvinceName = $event[0].name;
      this.formData.companyCityName = $event[1].name;
      this.formData.companyCountyName = $event[2].name;
    },

    getCategoryName () {
      const list = [...this.categoryChecked.list];
      if (this.categoryChecked.other) {
        list.push(this.categoryChecked.other);
      }
      return list.join('、');
    },

    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const loading = this.$loading();
          this.formData.categoryName = this.getCategoryName();

          try {
            await create(this.formData);
            loading.close();
            this.$alert('提交成功，我们会有专门的工作人员与您联系!');
            this.$router.back();
          } catch (error) {
            console.error(error);
            loading.close();
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.el-card {
  max-width: 890px;
  margin: 40px auto;
}

</style>
